package com.aiyan.edu.service.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: zqzhou
 * @create: 2019/11/12 22:10
 **/
@Configuration
public class ElasticsearchConfig {

    @Value("${es.hosts}")
    private String esHosts;

    private HttpHost[] buildHttpHosts() {
        String[] esHostsArr = esHosts.split(",");
        HttpHost[] httpHosts = new HttpHost[esHostsArr.length];

        for (int i = 0; i < esHostsArr.length; i++) {
            String eshost = esHostsArr[i];
            httpHosts[i] = new HttpHost(eshost.split(":")[0], Integer.parseInt(eshost.split(":")[1]), "http");
        }

        return httpHosts;
    }

    /**
     * 高级API客户端
     *
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(buildHttpHosts()));
    }

    /**
     * API客户端
     *
     * @return
     */
    @Bean
    public RestClient restClient() {
        return RestClient.builder(buildHttpHosts()).build();
    }
}
